﻿using System;
using System.Collections.Generic;
using System.Text;
using DIProject.DataSets;
using System.Data;
using System.Data.SqlClient;

namespace DIProject.Data
{
    /// <summary>
    /// класс для работы с накладными.
    /// </summary>
    public class Nkld
    {
        /// <summary>
        /// вставляем заголовок документа
        /// </summary>
        /// <returns></returns>
        public static waybillsData.SupplierInvoiceDocInsertDataTable SupplierInvoiceDocInsert
            (DateTime? DocData, string DocNumber, Int32? ContragentId, DateTime? ContragentDocDate, 
            string ContragentDocNumber,
            DateTime? PaymentDate,string Note,DateTime? MD,string MW)
        {
            if (!DocData.HasValue)
                throw new ArgumentException("docDate");
          /*  if (string.IsNullOrEmpty(DocNumber))
                throw new ArgumentException("docNumber");*/
            if (!ContragentId.HasValue)
                throw new ArgumentException("ContragentId");
            if (!ContragentDocDate.HasValue)
                throw new ArgumentException("ContragentDocDate");
            if (!PaymentDate.HasValue)
                throw new ArgumentException("PaymentDate");
            try
            {
                DataSets.waybillsDataTableAdapters.SupplierInvoiceDocInsertTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SupplierInvoiceDocInsertTableAdapter();
                waybillsData.SupplierInvoiceDocInsertDataTable dt = adapter.GetData(DocData, DocNumber, ContragentId, ContragentDocDate, ContragentDocNumber, PaymentDate, Note, MD, MW);
                if (dt.Count != 1)
                    throw new DIProject.Util.DIException("Невозможно создать шапку накладной");
                return dt;
            }
            catch (System.Data.SqlClient.SqlException se)
            {
                throw new DIProject.Util.DIException("Невозможно создать шапку накладной", se);
            }
            catch (Exception ee)
            {
                throw new DIProject.Util.DIException("Невозможно создать шапку накладной", ee);
            }
        }
        /// <summary>
        /// Вставляем строку накладной
        /// </summary>
        /// <param name="DocId"></param>
        /// <param name="GoodsId"></param>
        /// <param name="BarCode"></param>
        /// <param name="DocQntty"></param>
        /// <param name="Qntty"></param>
        /// <param name="SupplierGoodsId"></param>
        /// <param name="ManufacturePrice"></param>
        /// <param name="SupplierPrice"></param>
        /// <param name="ImportMarkup"></param>
        /// <param name="SupplierMarkap"></param>
        /// <param name="BatchNumber"></param>
        /// <param name="ReadyBefory"></param>
        /// <param name="MadeDate"></param>
        /// <param name="NDSTax"></param>
        /// <param name="NDSValue"></param>
        /// <param name="ReestrPrice"></param>
        /// <param name="ReestrDate"></param>
        /// <param name="GTDNumber"></param>
        /// <param name="CertificateNumber"></param>
        /// <param name="CertifikateDate"></param>
        /// <param name="CertifikateOrgId"></param>
        /// <param name="RetailMarkup"></param>
        /// <param name="RetailPrice"></param>
        /// <param name="Note"></param>
        /// <param name="MD"></param>
        /// <param name="MW"></param>
        /// <returns></returns>
        public static waybillsData.SupplierInvoiceLinesInsertDataTable SupplierInvoiceLinesInsert(Int32? DocId,
            Int32? GoodsId,string BarCode,Int32? DocQntty,Int32? Qntty,Int32? SupplierGoodsId,decimal? ManufacturePrice,
            decimal? SupplierPrice,decimal? SupplierSumNOTAX, double? ImportMarkup,double? SupplierMarkap,string BatchNumber,
            DateTime? ReadyBefory,DateTime? MadeDate,byte? NDSTax,decimal? NDSValue,decimal? ReestrPrice,
            DateTime? ReestrDate,string GTDNumber,string CertificateNumber,DateTime? CertifikateDate,
            Int32? CertifikateOrgId,double? RetailMarkup,decimal? RetailPrice,string Note,DateTime? MD,string MW)
        {
            if (!DocId.HasValue)
                throw new ArgumentException();
            if (!GoodsId.HasValue)
                throw new ArgumentException();
            if (!DocQntty.HasValue)
                throw new ArgumentException();
            if (!SupplierGoodsId.HasValue)
                throw new ArgumentException();
            /*if (!Qntty.HasValue)
            {
                if (!RetailPrice.HasValue)
                    throw new ArgumentException();
                if (!(RetailPrice.Value > 0))
                    throw new ArgumentException();
                if (Qntty.Value < 1)
                    throw new ArgumentException();
            }*/
            try
            {
                DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesInsertTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesInsertTableAdapter();
                waybillsData.SupplierInvoiceLinesInsertDataTable dt = adapter.GetData(DocId, GoodsId, BarCode,
                    DocQntty, Qntty, SupplierGoodsId, ManufacturePrice, SupplierPrice,SupplierSumNOTAX, ImportMarkup,
                    SupplierMarkap, BatchNumber, ReadyBefory, MadeDate, NDSTax, NDSValue, ReestrPrice, ReestrDate,
                    GTDNumber, CertificateNumber, CertifikateDate,null,/* CertifikateOrgId,*/ RetailMarkup,
                    RetailPrice, Note, MD, MW);
                if (dt.Count != 1)
                    throw new Util.DIException("Ошибка вставки строки накладной!");
                return dt;
            }
            catch (System.Data.SqlClient.SqlException se)
            {
                System.Diagnostics.Debug.WriteLine(se.ToString());
                throw new Util.DIException("Ошибка вставки строки накладной!", se);
            }
            catch (Exception ee)
            {
                throw new Util.DIException("Ошибка вставки строки накладной!", ee);
            }

        }
        public static void SupplierInvoiceDocUpdate(DateTime docDate,string docNumber,Int32 contragentId,
            DateTime? contragentDocDate, string contragentDocNumber, DateTime? paymentDate, string note,
            DateTime mD, string mW, Int32 original_Id, DateTime original_MD)
        {
            /*@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ContragentId int,
	@ContragentDocDate smalldatetime,
	@ContragentDocNumber varchar(20),
	@PaymentDate smalldatetime,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime*/
            string ConStr = Properties.Settings.Default.DIAptekaConnectionString;
            string commandText = "dbo.SupplierInvoiceDocUpdate";
            using (SqlConnection connection = new SqlConnection(ConStr))
            {
                try
                {
                    SqlCommand command = new SqlCommand();
                    command.CommandText = commandText;
                    command.CommandType = CommandType.StoredProcedure;
                    command.Connection = connection;
                    SqlParameter par = new SqlParameter("@DocDate", SqlDbType.SmallDateTime);
                    par.Value = docDate; command.Parameters.Add(par);
                    par = new SqlParameter("@DocNumber", SqlDbType.VarChar, 20);
                    par.Value = docNumber; command.Parameters.Add(par);
                    par = new SqlParameter("@ContragentId", SqlDbType.Int);
                    par.Value = contragentId; command.Parameters.Add(par);
                    par = new SqlParameter("@ContragentDocDate", SqlDbType.SmallDateTime);
                    if(contragentDocDate.HasValue)
                        par.Value = contragentDocDate; 
                    else
                        par.Value = DBNull.Value;
                    command.Parameters.Add(par);
                    par = new SqlParameter("@ContragentDocNumber", SqlDbType.VarChar, 20);
                    par.Value = contragentDocNumber; command.Parameters.Add(par);                    
                    par = new SqlParameter("@PaymentDate",SqlDbType.SmallDateTime);
                    if (paymentDate.HasValue)
                        par.Value = paymentDate;
                    else
                        par.Value = DBNull.Value;
                    command.Parameters.Add(par);
                    par = new SqlParameter("@Note",SqlDbType.VarChar,250);
                    par.Value = note; command.Parameters.Add(par);
                    par = new SqlParameter("@MD", SqlDbType.DateTime);
                    par.Value = mD; command.Parameters.Add(par);
                    par = new SqlParameter("@MW", SqlDbType.VarChar, 50);
                    par.Value = mW; command.Parameters.Add(par);
                    par = new SqlParameter("@Original_Id", SqlDbType.Int);
                    par.Value = original_Id; command.Parameters.Add(par);
                    par = new SqlParameter("@Original_MD", SqlDbType.DateTime);
                    par.Value = original_MD; command.Parameters.Add(par);
                    connection.Open();
                    Int32 tmp = command.ExecuteNonQuery();
                    if (tmp != 1)
                        throw new Util.DIException("Не удалось изменить заголовок накладной");

                }
                catch (SqlException se)
                {
                    System.Windows.Forms.MessageBox.Show("Не удалось изменить накладную\n" + se.Message, "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                catch (Exception ee)
                {
                    System.Windows.Forms.MessageBox.Show("Не удалось изменить накладную\n" + ee.Message, "Ошибка", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
        }
    }
}
